package com.xmxsuperstar.app.ttac.thread;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.xmxsuperstar.app.ttc.client.ClientConstants;
import com.xmxsuperstar.lib.utils.URLUtils;

public class ImageThread extends Thread {

	private final URL imgUrl;
	private final ImageView iv;

	private final Context context;
	private final Handler handler;

	public ImageThread(Context context, Handler handler, URL imgUrl,
			ImageView iv) {
		this.context = context;
		this.handler = handler;
		this.imgUrl = imgUrl;
		this.iv = iv;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void run() {
		try {
			Message msg = new Message();
			msg.what = 0;

			Bitmap bitmap = null;

			File cacheDir = context.getCacheDir();
			File bitmapFile = new File(cacheDir,
					URLUtils.getRequestPath(imgUrl));

			if (bitmapFile.exists() && bitmapFile.length() > 0) {
				bitmap = BitmapFactory.decodeStream(new FileInputStream(
						bitmapFile));
				Log.i(ClientConstants.LogTag, "Load pic : " + imgUrl
						+ "from cache file: " + bitmapFile.getAbsolutePath());
			} else {
				byte[] bt = getBytes(imgUrl.openStream());
				bitmap = BitmapFactory.decodeByteArray(bt, 0, bt.length);
				bitmapFile.getParentFile().mkdirs();
				bitmapFile.createNewFile();
				boolean result = bitmap.compress(CompressFormat.PNG, 100,
						new FileOutputStream(bitmapFile));
				Log.i(ClientConstants.LogTag, "compress bitmap: " + imgUrl
						+ "to cache file: " + bitmapFile.getAbsolutePath()
						+ "result: " + result);
			}

			List list = new ArrayList();// 将bitmap和imageView包装成一个List传到线程外
			list.add(bitmap);
			list.add(iv);
			msg.obj = list;
			handler.sendMessage(msg);
		} catch (Exception e) {
			Log.e(ClientConstants.LogTag, imgUrl + ":" + e.getMessage());
		}
	}

	private byte[] getBytes(InputStream is) throws IOException {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;

		while ((len = is.read(b, 0, 1024)) != -1) {
			baos.write(b, 0, len);
			baos.flush();
		}
		byte[] bytes = baos.toByteArray();
		return bytes;
	}
}
